package com.agileai.crm.module.procustomer.exteral;

import java.util.Date;
import java.util.List;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import com.agileai.common.KeyGenerator;
import com.agileai.crm.common.PrivilegeHelper;
import com.agileai.crm.cxmodule.OrgInfoManage;
import com.agileai.crm.cxmodule.ProcustVisitManage;
import com.agileai.crm.cxmodule.SalerListSelect;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.domain.FormSelectFactory;
import com.agileai.hotweb.domain.core.User;
import com.agileai.hotweb.ws.BaseRestService;
import com.agileai.util.DateUtil;
import com.agileai.util.StringUtil;


public class ProCustomerImpl extends BaseRestService implements ProCustomer {

	protected OrgInfoManage getService() {
		return (OrgInfoManage) this.lookupService(OrgInfoManage.class);
	}
	
	@Override
	public String findPotentialCustomerList(String searchWord) {
		String responseText = null;
		DataParam param = new DataParam();
		try {
    		if(!"".equals(searchWord)){
    			JSONObject searchObject = new JSONObject(searchWord);
	        	param.put("orgState", searchObject.get("orgState"));
	        	param.put("orgClassification", searchObject.get("orgClassification"));
	        	param.put("orgLabels", searchObject.get("orgLabels"));
    		}
        	
			JSONObject jsonObject = new JSONObject();
			User user = (User) getUser();
			PrivilegeHelper privilegeHelper = new PrivilegeHelper(user);
			if (!privilegeHelper.isSalesDirector()) {
				param.put("userId", user.getUserId());
			} else {
				param.put("userId", "");
			}
			
			String orgLabels = param.get("orgLabels");
			String sqlSyntax = " ";
			
			if (!StringUtil.isNullOrEmpty(orgLabels)){
				if ("Unlabeled".equals(orgLabels)){
					sqlSyntax = " and (a.ORG_LABELS is null or a.ORG_LABELS = '')";
				}
				else if ("Marked".equals(orgLabels)){
					sqlSyntax = " and (a.ORG_LABELS is not null and a.ORG_LABELS != '')";
				}else{
					sqlSyntax = " and a.ORG_LABELS='"+orgLabels+"'";
				}
			}
			param.put("sqlSyntax",sqlSyntax);
			
			List<DataRow> reList = getService().findRecords(param);
			JSONArray jsonArray = new JSONArray();
			for(int i=0;i<reList.size();i++){
				DataRow dataRow = reList.get(i);
				JSONObject jsonObject1 = new JSONObject();
				jsonObject1.put("id", dataRow.get("ORG_ID"));
				jsonObject1.put("name", dataRow.get("ORG_NAME"));
				String classification = FormSelectFactory.create("ORG_CLASSIFICATION").getText(dataRow.getString("ORG_CLASSIFICATION"));
				jsonObject1.put("classification", classification);
				jsonObject1.put("linkmanName", dataRow.get("ORG_LINKMAN_NAME"));
				String state = FormSelectFactory.create("PER_STATE").getText(dataRow.getString("ORG_STATE"));
				jsonObject1.put("state", state);
				jsonObject1.put("orgSalesmanName", dataRow.get("ORG_SALESMAN_NAME"));
				jsonObject1.put("updateTime", dataRow.get("ORG_UPDATE_TIME"));
				String labels = FormSelectFactory.create("ORG_LABELS").getText(dataRow.getString("ORG_LABELS"));
				jsonObject1.put("labels", labels);
				
				jsonArray.put(jsonObject1);
			}
			jsonObject.put("datas", jsonArray);
			responseText = jsonObject.toString();
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(),e);
		}
		return responseText;
	}

	@Override
	public String findPotentialCustomerSearch(String orgName) {
		String responseText = null;
		DataParam param = new DataParam();
		try {
			param.put("orgName",orgName);
			
			JSONObject jsonObject = new JSONObject();
			User user = (User) getUser();
			PrivilegeHelper privilegeHelper = new PrivilegeHelper(user);
			if (!privilegeHelper.isSalesDirector()) {
				param.put("userId", user.getUserId());
			} else {
				param.put("userId", "");
			}
			
			List<DataRow> reList = getService().findRecords(param);
			JSONArray jsonArray = new JSONArray();
			for(int i=0;i<reList.size();i++){
				DataRow dataRow = reList.get(i);
				JSONObject jsonObject1 = new JSONObject();
				jsonObject1.put("id", dataRow.get("ORG_ID"));
				jsonObject1.put("name", dataRow.get("ORG_NAME"));
				String classification = FormSelectFactory.create("ORG_CLASSIFICATION").getText(dataRow.getString("ORG_CLASSIFICATION"));
				jsonObject1.put("classification", classification);
				jsonObject1.put("linkmanName", dataRow.get("ORG_LINKMAN_NAME"));
				String state = FormSelectFactory.create("PER_STATE").getText(dataRow.getString("ORG_STATE"));
				jsonObject1.put("state", state);
				jsonObject1.put("orgSalesmanName", dataRow.get("ORG_SALESMAN_NAME"));
				jsonObject1.put("updateTime", dataRow.get("ORG_UPDATE_TIME"));
				String labels = FormSelectFactory.create("ORG_LABELS").getText(dataRow.getString("ORG_LABELS"));
				jsonObject1.put("labels", labels);
				
				jsonArray.put(jsonObject1);
			}
			jsonObject.put("datas", jsonArray);
			responseText = jsonObject.toString();
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(),e);
		}
		return responseText;
	}

	@Override
	public String addPotentialCustomer(String info) {
    	String responseText = "fail";
    	try {
        	JSONObject jsonObject = new JSONObject(info);
        	User user = (User) this.getUser();
        	String userId = user.getUserId();
        	String nowTime = DateUtil.getDateByType(DateUtil.YYMMDDHHMI_HORIZONTAL, new Date());
        	
        	String orgId = KeyGenerator.instance().genKey();
        	String orgName = jsonObject.get("orgName").toString();
        	String orgClassification = jsonObject.get("orgClassification").toString();
        	String orgType = jsonObject.get("orgType").toString();
        	String orgSources = jsonObject.get("orgSources").toString();
        	String orgLinkmanName = jsonObject.get("orgLinkmanName").toString();
        	String orgEmail = jsonObject.get("orgEmail").toString();
        	String orgLabels = jsonObject.get("orgLabels").toString();
        	String orgWebsite = jsonObject.get("orgWebsite").toString();
        	String orgSalesman = userId;
        	String orgState = jsonObject.get("orgState").toString();
        	String orgCreater = userId;
        	String orgCreateTime = nowTime;
        	String orgUpdateTime = nowTime;
        	String orgContactWay = jsonObject.get("orgContactWay").toString();
        	String orgAddress = jsonObject.get("orgAddress").toString();
        	String orgIntroduction = jsonObject.get("orgIntroduction").toString();

        	
        	DataParam createParam = new DataParam("ORG_ID",orgId,"ORG_NAME",orgName,"ORG_TYPE",orgType,"ORG_INTRODUCTION",orgIntroduction,"ORG_LINKMAN_NAME",orgLinkmanName,
        			"ORG_EMAIL",orgEmail,"ORG_CONTACT_WAY",orgContactWay,"ORG_SOURCES",orgSources,"ORG_STATE",orgState,"ORG_LABELS",orgLabels,"ORG_CREATER",orgCreater,
        			"ORG_CREATE_TIME",orgCreateTime,"ORG_ADDRESS",orgAddress,"ORG_WEBSITE",orgWebsite,"ORG_UPDATE_TIME",orgUpdateTime,"ORG_CLASSIFICATION",orgClassification,
        			"ORG_SALESMAN",orgSalesman);
        	getService().createRecord(createParam);
        	
        	responseText = "success";
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
    	return responseText;
    }
	
	@Override
	public String editPotentialCustomer(String info) {
    	String responseText = "fail";
    	try {
        	JSONObject jsonObject = new JSONObject(info);
        	String nowTime = DateUtil.getDateByType(DateUtil.YYMMDDHHMI_HORIZONTAL, new Date());
        	
        	String orgId = jsonObject.get("orgId").toString();
        	String orgName = jsonObject.get("orgName").toString();
        	String orgClassification = jsonObject.get("orgClassification").toString();
        	String orgType = jsonObject.get("orgType").toString();
        	String orgSources = jsonObject.get("orgSources").toString();
        	String orgLinkmanName = jsonObject.get("orgLinkmanName").toString();
        	String orgEmail = jsonObject.get("orgEmail").toString();
        	String orgLabels = jsonObject.get("orgLabels").toString();
        	String orgWebsite = jsonObject.get("orgWebsite").toString();
        	String orgSalesman = jsonObject.get("orgSalesman").toString();;
        	String orgState = jsonObject.get("orgState").toString();
        	String orgCreater = jsonObject.get("orgCreater").toString();
        	String orgCreateTime = jsonObject.get("orgCreateTime").toString();
        	String orgUpdateTime = nowTime;
        	String orgContactWay = jsonObject.get("orgContactWay").toString();
        	String orgAddress = jsonObject.get("orgAddress").toString();
        	String orgIntroduction = jsonObject.get("orgIntroduction").toString();

        	
        	DataParam updateParam = new DataParam("ORG_ID",orgId,"ORG_NAME",orgName,"ORG_TYPE",orgType,"ORG_INTRODUCTION",orgIntroduction,"ORG_LINKMAN_NAME",orgLinkmanName,
        			"ORG_EMAIL",orgEmail,"ORG_CONTACT_WAY",orgContactWay,"ORG_SOURCES",orgSources,"ORG_STATE",orgState,"ORG_LABELS",orgLabels,"ORG_CREATER",orgCreater,
        			"ORG_CREATE_TIME",orgCreateTime,"ORG_ADDRESS",orgAddress,"ORG_WEBSITE",orgWebsite,"ORG_UPDATE_TIME",orgUpdateTime,"ORG_CLASSIFICATION",orgClassification,
        			"ORG_SALESMAN",orgSalesman);
        	getService().updateRecord(updateParam);
        	
        	responseText = "success";
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
    	return responseText;
    }

	@Override
	public String getPotentialCustomerinfo(String id) {
		String responseText = null;
		try {
			JSONObject jsonObject = new JSONObject();
			DataRow dataRow = getService().getRecord(new DataParam("ORG_ID",id));
			String orgId = dataRow.getString("ORG_ID");
			jsonObject.put("orgId", orgId);
			jsonObject.put("orgName", dataRow.get("ORG_NAME"));
			jsonObject.put("orgClassification", dataRow.get("ORG_CLASSIFICATION"));
			jsonObject.put("orgType", dataRow.get("ORG_TYPE"));
			jsonObject.put("orgSources", dataRow.get("ORG_SOURCES"));
			jsonObject.put("orgLinkmanName", dataRow.get("ORG_LINKMAN_NAME"));
			jsonObject.put("orgEmail", dataRow.get("ORG_EMAIL"));
			jsonObject.put("orgLabels", dataRow.get("ORG_LABELS"));
			jsonObject.put("orgWebsite", dataRow.get("ORG_WEBSITE"));
			jsonObject.put("orgSalesman", dataRow.get("ORG_SALESMAN"));
			jsonObject.put("orgSalesmanName", dataRow.get("ORG_SALESMAN_NAME"));
			jsonObject.put("orgState", dataRow.get("ORG_STATE"));
			jsonObject.put("orgCreater", dataRow.get("ORG_CREATER"));
			jsonObject.put("orgCreaterName", dataRow.get("ORG_CREATER_NAME"));
			jsonObject.put("orgCreateTime", dataRow.get("ORG_CREATE_TIME"));
			jsonObject.put("orgUpdateTime", dataRow.get("ORG_UPDATE_TIME"));
			jsonObject.put("orgContactWay", dataRow.get("ORG_CONTACT_WAY"));
			jsonObject.put("orgAddress", dataRow.get("ORG_ADDRESS"));
			jsonObject.put("orgIntroduction", dataRow.get("ORG_INTRODUCTION"));
			jsonObject.put("orgVisitAgainTime", dataRow.get("ORG_VISIT_AGAIN_TIME"));
			
			ProcustVisitManage service = this.lookupService(ProcustVisitManage.class);
			List<DataRow> rsList = service.findRecords(new DataParam("ORG_ID",orgId));
			JSONArray jsonArray = new JSONArray();
			for(int i=0;i<rsList.size();i++){
				DataRow dataRow1 = rsList.get(i);
				JSONObject jsonObject1 = new JSONObject();
				jsonObject1.put("id", dataRow1.get("PROCUST_VISIT_ID"));
				String date = DateUtil.format(DateUtil.YYMMDD_HORIZONTAL, dataRow1.getTimestamp("PROCUST_VISIT_DATE"));
				jsonObject1.put("date", date);
				jsonObject1.put("fillName", dataRow1.get("PROCUST_VISIT_FILL_NAME"));
				String fillTime = DateUtil.format(DateUtil.YYMMDDHHMI_HORIZONTAL, dataRow1.getTimestamp("PROCUST_VISIT_FILL_TIME"));
				jsonObject1.put("fillTime", fillTime);
				String effect = FormSelectFactory.create("VISIT_EFFECT").getText(dataRow1.getString("PROCUST_VISIT_EFFECT"));
				jsonObject1.put("effect", effect);
				String type = FormSelectFactory.create("VISIT_TYPE").getText(dataRow1.getString("PROCUST_VISIT_TYPE"));
				jsonObject1.put("type", type);
				String category = FormSelectFactory.create("CUST_VISIT_CATEGORY").getText(dataRow1.getString("CUST_VISIT_CATEGORY"));
				jsonObject1.put("category", category);
				
				jsonArray.put(jsonObject1);
			}
			
			jsonObject.put("visitList", jsonArray);
			responseText = jsonObject.toString();
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(),e);
		}
		return responseText;
	}

	@Override
	public String getPotentialVisitingRecord(String id, String category) {
		String responseText = null;
		try {
			
			ProcustVisitManage service = this.lookupService(ProcustVisitManage.class);
			DataRow dataRow = new DataRow();
			if("PRO_CUST".equals(category)){
				dataRow = service.getRecord(new DataParam("PROCUST_VISIT_ID",id));
			}else if("FOLLOW_CUST".equals(category)){
				dataRow = service.getCustRecord(new DataParam("PROCUST_VISIT_ID",id));
			}
			
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("id", id);
			String date = DateUtil.getDateByType(DateUtil.YYMMDD_HORIZONTAL, (Date) dataRow.get("PROCUST_VISIT_DATE"));
			jsonObject.put("date", date);
			jsonObject.put("fillName", dataRow.get("PROCUST_VISIT_FILL_NAME"));
			String fillTime = DateUtil.getDateByType(DateUtil.YYMMDDHHMI_HORIZONTAL, (Date) dataRow.get("PROCUST_VISIT_FILL_TIME"));
			jsonObject.put("fillTime", fillTime);
			String effect = FormSelectFactory.create("VISIT_EFFECT").getText(dataRow.getString("PROCUST_VISIT_EFFECT"));
			jsonObject.put("effect", effect);
			String type = FormSelectFactory.create("VISIT_TYPE").getText(dataRow.getString("PROCUST_VISIT_TYPE"));
			jsonObject.put("type", type);
			jsonObject.put("remark", dataRow.get("PROCUST_VISIT_REMARK"));
			jsonObject.put("custFocus", dataRow.get("PROCUST_VISIT_CUST_FOCUS"));
			String visitCategory = FormSelectFactory.create("CUST_VISIT_CATEGORY").getText(dataRow.getString("CUST_VISIT_CATEGORY"));
			jsonObject.put("category", visitCategory);
			
			responseText = jsonObject.toString();
		} catch (JSONException e) {
			log.error(e.getLocalizedMessage(),e);
		}
		
		return responseText;
	}

	@Override
	public String deletePotentialCustomer(String id) {
    	String responseText = "fail";
    	try {
        	getService().deletRecord(new DataParam("ORG_ID",id));
        	responseText = "success";
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
    	return responseText;
    }

	@Override
	public String assignPotentialCustomer(String id, String saleId) {
		String responseText = "fail";
    	DataParam idParam = new DataParam();
    	idParam.put("ORG_ID", id);
    	idParam.put("ORG_SALESMAN", saleId);
    	getService().assignedSaleRecord(idParam);
    	responseText = "success";
		return responseText;
	}

	@Override
	public String findSaleList(String saleName) {
		String responseText = null;
		try {
			DataParam param = new DataParam();
			JSONObject searchObject = new JSONObject(saleName);
			String userName = searchObject.optString("saleName","");
			if(!"".equals(userName)){
				param.put("userName", userName);
			}
			
			SalerListSelect service = this.lookupService(SalerListSelect.class);
			List<DataRow> rsList = service.queryPickFillRecords(param);
			JSONArray jsonArray = new JSONArray();
			
			for(int i=0;i<rsList.size();i++){
				DataRow dataRow = rsList.get(i);
				JSONObject jsonObject = new JSONObject();
				
				jsonObject.put("userId", dataRow.getString("USER_ID"));
				jsonObject.put("userName", dataRow.getString("USER_NAME"));
				jsonArray.put(jsonObject);
			}
			
			responseText = jsonArray.toString();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return responseText;
	}
}
